class Group < ActiveRecord::Base
  #has_and_belongs_to_many :users
  has_many :group_users, :dependent => :destroy
  has_many :users, :through => :group_users
  
  has_many :group_posts
  file_column :image, :magick => { 
          #:versions => { "thumb" => "40x40", "medium" => "640x480>" }
          :versions => { 
          		:square => { :crop => "1:1", :size => "40x40", :name => "thumb"},
          		:screen => {:crop => "1:1", :size => "640x480", :name => "medium"},
          }
  }
  
  validates_presence_of     :title, :message => "小组标题不能为空"
  validates_presence_of     :description, :message => "小组描述不能为空"
  validates_length_of       :title,    :within => 3..100, :too_long => "小组标题在3到100位之间", :too_short => "小组标题在3到100位之间"
  validates_length_of       :description,    :within => 5..2000, :too_long => "小组描述在5到2000位之间", :too_short => "小组描述在5到2000位之间"
  
  analyzer = Ferret::Analysis::PerFieldAnalyzer.new(Ferret::Analysis::StandardAnalyzer.new)
  analyzer[:title] = Ferret::Analysis::RegExpAnalyzer.new(/./, false)
  analyzer[:content] = Ferret::Analysis::RegExpAnalyzer.new(/./, false)
  #acts_as_ferret({:fields => [ 'title', 'description' ]},
  #					{:analyzer=> analyzer})
  acts_as_ferret({:fields => {:title => {:store => :yes}, :description => {:store => :yes}}}, {:analyzer=> analyzer})
  
  cattr_reader :per_page
  @@per_page = 15
  
  def has_two_admin
    num_of_admins > 0
  end
  
  def num_of_admins
    User.count_by_sql("select count(*) from users, group_users" + 
    				  " where users.id = group_users.user_id" +
    				  " and group_users.group_id = " + self.id.to_s +
    				  " and group_users.is_admin = 't'")
  end
  
  def is_admin?(user)
   	return false if user.nil?
    groups = Group.count_by_sql("select count(*) from users inner join group_users" +
    				  " on is_admin = 't'" +
    				  " and group_id = " + self.id.to_s +
    				  " where users.id = group_users.user_id" +
    				  " and users.id = "+user.id.to_s)
    groups > 0
  end
  
  def before_save
    self.title = self.title.gsub(/^\<(script|frame)/i, '')
    self.description = self.description.gsub(/^\<(script|frame)/i, '')
  end
end
